<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
		<!-- 引入样式 -->
		<link rel="stylesheet" href="../../plugins/element-ui/index.css" />
		<link rel="stylesheet" href="../../styles/common.css" />
		<link rel="stylesheet" href="../../styles/page.css" />
		<style>
			.selectInput {
				position: relative;
				width: 100%;
				min-width: 100px;
			}

			.selectInput .flavorSelect {
				position: absolute;
				width: 100%;
				padding: 0 10px;
				border-radius: 3px;
				border: solid 1px #FF903D;
				line-height: 30px;
				text-align: center;
				background: #fff;
				top: 50px;
				z-index: 99;
			}

			.selectInput .flavorSelect .items {
				cursor: pointer;
				display: inline-block;
				width: 100%;
				line-height: 35px;
				border-bottom: solid 1px #f4f4f4;
				color: #666;
			}

			.selectInput .flavorSelect .none {
				font-size: 14px;
			}

			#food-add-app .uploadImg .el-form-item__label::before {
				content: '*';
				color: #F56C6C;
				margin-right: 4px;
			}
		</style>
	</head>
	<body>

		<div class="addBrand-container" id="teacher-update-app">
			<div class="container">
				<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :inline="true" label-width="180px"
					class="demo-ruleForm">
					<h1>编辑老师信息</h1>
					<div>
						<el-form-item label="账号名:" prop="username">
							<el-input v-model="ruleForm.sysUser.username" placeholder="请填写老师账号名" maxlength="20" />
						</el-form-item>
					</div>
					<!-- <div>
						<el-form-item label="账号密码:" prop="username">
							<el-input v-model="ruleForm.sysUser.password" type="password" placeholder="请填写老师账号登录密码" maxlength="40" />
						</el-form-item>
					</div> -->
					<div>
						<el-form-item label="账户昵称:" prop="nickname">
							<el-input v-model="ruleForm.sysUser.nickname" placeholder="请填写老师昵称" maxlength="20" />
						</el-form-item>
					</div>
					<div>
						<el-form-item label="老师名称:" prop="username2">
							<el-input v-model="ruleForm.username" placeholder="请填写老师名字" maxlength="20" />
						</el-form-item>
					</div>
					<div>
						<div>
							<el-form-item label="头像:" prop="head" class="uploadImg">
								<el-upload class="avatar-uploader" action="/apis/common/upload" :show-file-list="false"
									:on-success="handleAvatarSuccess" :on-change="onChange" ref="upload">
									<img v-if="imageUrl" :src="imageUrl" class="avatar">
									<i v-else class="el-icon-plus avatar-uploader-icon"></i>
								</el-upload>
							</el-form-item>
						</div>
					</div>
					<div>
						<div>
							<el-form-item label="形象照:" prop="sysUser.images" class="uploadImg">
								<el-upload class="avatar-uploader" action="/apis/common/upload" :show-file-list="false"
									:on-success="handleAvatarSuccess2" :on-change="onChange" ref="upload2">
									<img v-if="imageUrl2" :src="imageUrl2" class="avatar">
									<i v-else class="el-icon-plus avatar-uploader-icon"></i>
								</el-upload>
							</el-form-item>
						</div>
					</div>
					<div>
						<el-form-item label="年龄:" prop="age">
							<el-input v-model="ruleForm.sysUser.age" placeholder="请填写老师年龄" maxlength="20" />
						</el-form-item>
					</div>
					<div>
						<el-form-item label="性别:" prop="gender">
							<el-radio-group v-model="ruleForm.sysUser.gender">
								<el-radio label="男">男</el-radio>
								<el-radio label="女">女</el-radio>
							</el-radio-group>
						</el-form-item>
					</div>

					<div>
						<el-form-item label="老师生日:" prop="birthday">
							<el-date-picker v-model="ruleForm.sysUser.birthday" type="date" placeholder="选择日期" @change="timeupdate()">
							</el-date-picker>
						</el-form-item>
					</div>

					<div>
						<el-form-item label="身份证号:" prop="idNumber">
							<el-input v-model="ruleForm.sysUser.idNumber" placeholder="请填写老师身份证号" maxlength="20" />
						</el-form-item>
					</div>
					<div>
						<el-form-item label="电话:" prop="phone">
							<el-input v-model="ruleForm.sysUser.phone" placeholder="请填写老师电话" maxlength="20" />
						</el-form-item>
					</div>
					<div>
						<el-form-item label="邮箱:" prop="email">
							<el-input v-model="ruleForm.sysUser.email" placeholder="请填写老师邮箱" maxlength="20" />
						</el-form-item>
					</div>
					<div>
						<el-form-item label="店铺名称:" prop="shopkeeperName">
							<el-select v-model="ruleForm.shopkeeperName" placeholder="请选择店铺" @change="selectShopkeeperName"
								style="width: 150px;margin-right: 10px;">
								<el-option label="" value="">取消选择</el-option>
								<el-option :label="item.shopkeeperName" :value="item" v-for="(item,index) in shopkeeperNameList">
									{{item.shopkeeperName}}
								</el-option>
							</el-select>
						</el-form-item>
					</div>
					<div>
						<el-form-item label="老师标签" prop="tag">
							<el-select v-model="ruleForm.tag" multiple placeholder="请选择标签">
								<el-option v-for="tag in tagOptions" :key="tag" :label="tag" :value="tag">
								</el-option>
							</el-select>
						</el-form-item>
					</div>

					<div>
						<el-form-item label="等级:" prop="levels">
							<el-select v-model="ruleForm.levels" placeholder="请选择">
								<el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.label">
								</el-option>
							</el-select>
						</el-form-item>
					</div>

					<div>
						<el-form-item label="工作时间:" prop="workTime">
							<el-input v-model="ruleForm.workTime" placeholder="请填写老师工作经验年限" maxlength="20" />
						</el-form-item>
					</div>
					<div>
						<el-form-item label="擅长:" prop="good">
							<el-input v-model="ruleForm.good" placeholder="请填写老师擅长" maxlength="20" />
						</el-form-item>
					</div>
					<div>
						<el-form-item label="经历:" prop="experience">
							<el-input v-model="ruleForm.experience" placeholder="请填写老师经历" maxlength="20" />
						</el-form-item>
					</div>
					<div class="subBox address">
						<el-form-item>
							<el-button @click="goBack()">取消</el-button>
							<el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
							<el-button v-if="actionType == 'add'" type="primary" class="continue"
								@click="submitForm('ruleForm','goAnd')">
								保存并继续添加老师
							</el-button>
						</el-form-item>
					</div>

				</el-form>
				<h1 style="margin-top: 30px;">老师的课程信息</h1>
				<el-table :data="tableData" stripe class="tableBox" @selection-change="handleSelectionChange" max-height="500">
					<el-table-column prop="courseName" label="课程名称"></el-table-column>
					<el-table-column prop="tag" label="课程标签"></el-table-column>
					<el-table-column prop="difficulty" label="课程难度"></el-table-column>
					<el-table-column prop="room" label="教室名称"></el-table-column>
					<el-table-column label="状态">
						<template slot-scope="scope">
							<span style="margin-right: 10px;">{{ scope.row.status == '0' ? '停用' : '启用' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="duration" label="课程时长"></el-table-column>
					<el-table-column prop="startTime" label="开始时间"></el-table-column>
					<el-table-column prop="endTime" label="结束时间"></el-table-column>
					<el-table-column prop="courseDate" label="开课日期"></el-table-column>
					<el-table-column prop="nowPerson" label="已报人数"></el-table-column>
					<el-table-column prop="maxPerson" label="上限人数"></el-table-column>
				</el-table>
			</div>
		</div>
		<!-- 开发环境版本，包含了有帮助的命令行警告 -->
		<script src="../../plugins/vue/vue.js"></script>
		<!-- 引入组件库 -->
		<script src="../../plugins/element-ui/index.js"></script>
		<!-- 引入axios -->
		<script src="../../plugins/axios/axios.min.js"></script>
		<script src="../../js/request.js"></script>
		<script src="../../js/validate.js"></script>
		<script src="../../js/index.js"></script>
		<script src="../../api/teacher.js"></script>
		<script src="../../api/shop.js"></script>
		<script src="../../js/common.js"></script>
		<script src="../../api/shopkeeper.js"></script>
		<script>
			new Vue({
				el: '#teacher-update-app',
				data() {
					return {
						tableData: [],
						teacherId:"",
						imageUrl: '',
						imageUrl2: '',
						actionType: '',
						levelOptions: [{
								value: '1',
								label: '初级'
							},
							{
								value: '2',
								label: '中级'
							},
							{
								value: '3',
								label: '高级'
							}
						],
						ruleForm: {
							teacherId: '',
							username: '',
							name: '',
							nickname: '',
							age: '',
							gender: '',
							birthday: '',
							idNumber: '',
							phone: '',
							email: '',
							shopkeeperId: '',
							tag: '',
							levels: '',
							workTime: '',
							good: '',
							experience: '',
							head: '',
							images: '',
							sysUser: {
								addr: "",
								age: "",
								birthday: "",
								email: "",
								gender: "",
								idNumber: "",
								name: "",
								phone: "",
								username: "",
								tag: ""
							}
						},
						shopkeeperNameList: [],
						tagOptions: []
					}
				},
				computed: {
					rules() {
						return {
							// 'name': [
							//     {'required': true, 'message': '请填写名称', 'trigger': 'blur'}
							// ]
							// "name": [
							//     {required: true, message: '请填写名称', trigger: 'blur'}
							// ],
							// idNumber: [
							//     {required: true, message: '请填写身份证号', trigger: 'blur'},
							//     {validator: this.validateIdNumber, trigger: 'blur'}
							// ],
							// phone: [
							//     {required: true, message: '请填写电话', trigger: 'blur'},
							//     {validator: this.validatePhone, trigger: 'blur'}
							// ],
							// email: [
							//     {required: true, message: '请填写邮箱', trigger: 'blur'},
							//     {type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change']}
							// ]
						}
					}
				},
				created() {
					this.teacherId = requestUrlParam('userId');
					this.source = requestUrlParam('source')
					this.actionType = this.teacherId ? 'edit' : 'add';
					if (this.teacherId) {
						this.init()
					}
					//根据标签类型获取标签名字
					getTagListByType("老师").then(res => {
						this.tagOptions = res.data;
					})
					this.selectClasses();
					//和修改相关
					this.teacherId = requestUrlParam('userId');
					this.getAllShopkeeperName()
				},

				mounted() {},
				methods: {
					//店铺选择赋值
					selectShopkeeperName(v) {
						console.log(v)
						this.ruleForm.shopkeeperId = v.shopkeeperId
						this.ruleForm.shopkeeperName = v.shopkeeperName
					},
					//查询店铺名称
					getAllShopkeeperName() {
						getAllShopkeeperNameId().then(res => {
							this.shopkeeperNameList = res.data;
						})
					},
					turnShop(item) {
						console.log(item);
						this.ruleForm.shopkeeperId = item.shopkeeperId
					},
					handleAvatarSuccess(response, file, fileList) {
						this.imageUrl = `/apis/common/download?name=${response.data}`;
						this.ruleForm.sysUser.head = response.data
					},
					handleAvatarSuccess2(response, file, fileList) {
						this.imageUrl2 = `/apis/common/download?name=${response.data}`;
						this.ruleForm.head = response.data
					},
					async init() {
						var _this = this
						//根据用户id查询老师
						queryTeacherById(this.teacherId).then(res => {
							if (String(res.code) === '1') {
								this.ruleForm = res.data
								this.ruleForm.tag = (res.data.tag ? res.data.tag.split(',') : [])
								this.imageUrl = $minioUrl + "" + res.data.head
								this.imageUrl2 = $minioUrl + "" + res.data.sysUser.head
							} else {
								this.$message.error(res.msg || '操作失败')
							}
						})
					},
					timeupdate() {
						var t = dateFormat("yyyy-MM-dd", this.ruleForm.birthday)
						this.ruleForm.birthday = t
					},
					selectClasses() {
						console.log('Fetching classes for teacher ID:', this.teacherId);
						getByIdWithClasses(this.teacherId).then(res => {
							console.log('API Response:', res);
							if (String(res.code) === '1') {
								console.log('Response data:', res.data);
								this.tableData = Array.isArray(res.data) ? res.data : [res.data];
							} else {
								console.error('API Error:', res.msg);
								this.$message.error(res.msg || '获取课程数据失败');
								this.tableData = []; // 清空表格或显示默认数据
							}
						}).catch(error => {
							console.error('Request failed:', error);
							this.$message.error('请求失败: ' + error.message);
						});
					},
					submitForm(formName, st) {
						this.$refs[formName].validate((valid) => {if (valid) {
								const params = {
									...this.ruleForm
								};
								// tag 类型转换
								params.tag = this.ruleForm.tag.join(",")
								// 账户类型直接设置 老师
								params.sysUser.type = "老师"
								// 账户状态 启用
								params.sysUser.status = 1;
								// 照片赋值
								// this.ruleForm.head = this.ruleForm.sysUser.images
								editTeacher(params).then(res => {
									if (res.code === 1) {
										this.$message({
											message: '老师修改成功！',
											type: 'success',
											duration: 1200, // 设置显示时间1.5秒
											onClose: () => {
												if (source === 'teacher') {
													window.parent.goBack();
												} else {
													window.parent.goBack();
												}
											}
										});
									} else {
										this.$message.error(res.msg || '操作失败');
									}
								}).catch(err => {
									this.$message.error('请求出错了：' + err);
								});
							} else {
								return false;
							}
						});
					},
					onChange(file) {
						if (file) {
							const suffix = file.name.split('.')[1];
							const size = file.size / 1024 / 1024 < 2;
							if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
								this.$message.error('上传图片只支持 png、jpeg、jpg 格式！');
								this.$refs.upload.clearFiles();
								return false
							}
							if (!size) {
								this.$message.error('上传文件大小不能超过 2MB!');
								return false
							}
							return file
						}
					},
					goBack() {
						window.parent.menuHandle({
							id: '4',
							url: 'page/teacher/list.html',
							name: '教师管理'
						}, false)

					},
					goBack2() {
						const id = new URLSearchParams(window.location.search).get('id');
						window.parent.menuHandle({
								id: '12',
								url: 'page/stadium/detail.html',
								name: '店铺详情'
							},
							true,
							null, {
								id
							}
						);
					},
					beforeAvatarUpload(file) {
						const isJPG = file.type === 'image/jpeg';
						const isLt2M = file.size / 1024 / 1024 < 2;
						if (!isLt2M) {
							this.$message.error('上传头像图片大小不能超过 2MB!');
						}
						return isJPG && isLt2M;
					},
					// 验证身份证号 (18位)
					validateIdNumber(rule, value, callback) {
						if (!value) {
							callback(new Error('请填写身份证号'));
						} else if (!/^\d{17}[\dXx]$/.test(value)) {
							callback(new Error('请输入18位有效身份证号'));
						} else {
							callback();
						}
					},

					// 验证手机号 (11位)
					validatePhone(rule, value, callback) {
						if (!value) {
							callback(new Error('请填写电话'));
						} else if (!/^1[3-9]\d{9}$/.test(value)) {
							callback(new Error('请输入11位有效手机号码'));
						} else {
							callback();
						}
					},
					// 验证电子邮件
					validateEmail(rule, value, callback) {
						if (!value) {
							callback(new Error('请填写邮箱'));
						} else if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)) {
							callback(new Error('请输入有效的邮箱地址'));
						} else {
							callback();
						}
					},
					// 全部操作
					handleSelectionChange(val) {
						let checkArr = [];
						val.forEach((n) => {
							checkArr.push(n.id)
						});
						this.checkList = checkArr
					},
				}
			})
		</script>
	</body>
</html>